package com.hmall.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.pojo.Item;
import com.hmall.item.mapper.ItemMapper;

import com.hmall.item.service.IItemService;
import org.springframework.stereotype.Service;

@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {

    /*@Autowired
    private RestHighLevelClient restHighLevelClient;
    *//**
     * 自动补全
     * @param key
     * @return
     *//*
    @Override
    public List<String> suggestion(String key) {
        //创建请求
        SearchRequest request = new SearchRequest("item");
        //DSL
        request.source().suggest(new SuggestBuilder().addSuggestion(
                "MySuggestion",
                SuggestBuilders.completionSuggestion("suggestion")
                .prefix(key)
                .size(10)
                .skipDuplicates(true)
        ));
        //发送请求
        SearchResponse response = null;
        try {
            response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //解析结果
        Suggest suggest = response.getSuggest();
        CompletionSuggestion suggestion = suggest.getSuggestion("MySuggestion");
        List<String> list = new ArrayList<>();
        for (CompletionSuggestion.Entry.Option option : suggestion.getOptions()) {
            String s = option.getText().string();
            list.add(s);
        }
        return list;
    }

    *//**
     * 过滤项聚合
     * @param dto
     * @return
     *//*
    @Override
    public Map<String, List<String>> filters(RequestParams dto) {
        Map<String, List<String>> resultMap = new HashMap<>();
        //创建请求对象
        SearchRequest request = new SearchRequest("item");
        //限定聚合范围
        basicSearch(dto,request);
        //设定文档数
        request.source().size(0);
        //构建agg
        buildAgg(request);
        //发送请求
        SearchResponse response = null;
        try {
            response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        List<String> category_agg = parseAgg(response, "category_agg");
        List<String> brand_agg = parseAgg(response, "brand_agg");
        resultMap.put("category",category_agg);
        resultMap.put("brand",brand_agg);
        return resultMap;
    }

    *//**
     * 搜索
     * @param dto
     * @return
     *//*
    @Override
    public PageDTO<ItemDoc> list(RequestParams dto) {
        //创建请求对象
        SearchRequest request = new SearchRequest("item");
        basicSearch(dto,request);
        //分页
        Integer page = dto.getPage();
        Integer size = dto.getSize();
        request.source().from((page-1)*size).size(size);
        //排序
        String sortBy = dto.getSortBy();
        if ("sold".equals(sortBy)){
            request.source().sort("sold", SortOrder.ASC);
        }else if ("price".equals(sortBy)){
            request.source().sort("price",SortOrder.ASC);
        }
        //发送请求
        SearchResponse response = null;
        try {
            response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //解析结果
        SearchHits searchHits = response.getHits();
        //总数
        long total = searchHits.getTotalHits().value;
        SearchHit[] hits = searchHits.getHits();
        List<ItemDoc> list = new ArrayList<>();
        for (SearchHit hit : hits) {
            String s = hit.getSourceAsString();
            //反序列化
            ItemDoc itemDoc = JSON.parseObject(s, ItemDoc.class);
            list.add(itemDoc);
        }
        return new PageDTO<>(total,list);
    }

    *//**
     * 解析agg结果
     * @param response
     * @param aggName
     * @return
     *//*
    private List<String> parseAgg(SearchResponse response, String aggName) {
        //解析响应
        Aggregations aggregations = response.getAggregations();
        //根据名称获取聚合结果
        Terms terms = aggregations.get(aggName);
        //获取桶
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        //遍历
        List<String> list = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String keyAsString = bucket.getKeyAsString();
            list.add(keyAsString);
        }
        return list;
    }

    *//**
     * 构建agg
     * @param request
     *//*
    private void buildAgg(SearchRequest request) {
        //bucket聚合
        request.source().aggregation(AggregationBuilders
                .terms("category_agg")
                .field("category")
                .size(20)
                .order(BucketOrder.count(false)));
        request.source().aggregation(AggregationBuilders
                .terms("brand_agg")
                .field("brand")
                .size(20)
                .order(BucketOrder.count(false)));
    }

    *//**
     * 基本查询
     * @param dto
     * @param request
     *//*
    private void basicSearch(RequestParams dto,SearchRequest request) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        String key = dto.getKey();
        if (!StringUtils.isEmpty(key)) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all",key));
        }else {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }
        //分类
        String category = dto.getCategory();
        if (!StringUtils.isEmpty(category)){
            boolQueryBuilder.filter(QueryBuilders.termQuery("category",category));
        }
        //品牌
        String brand = dto.getBrand();
        if (!StringUtils.isEmpty(brand)){
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand",brand));
        }
        //价格
        Integer minPrice = dto.getMinPrice();
        Integer maxPrice = dto.getMaxPrice();
        if (minPrice!=null && maxPrice!=null){
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(minPrice*100).lte(maxPrice*100));
        }
        //算分函数
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                //原始查询,相关性算分的查询
                boolQueryBuilder,
                //function score的数组
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        //其中的一个function score元素
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                //过滤条件
                                QueryBuilders.termQuery("isAD", true),
                                //算分函数
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                });
        request.source().query(functionScoreQuery);
    }*/
}
